<template>
  <div>
    <div style="text-align: end; margin-bottom: 10px">
      <a-space>
        <a-button type="primary" @click="handleBindPrams">
          <template #icon>
            <icon-link />
          </template>
          绑定参数
        </a-button>
      </a-space>
    </div>
    <a-spin :loading="data.loading">
      <a-table :data="data.tableData" :columns="data.columns" :pagination="false">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #status="{ record }">
          <template v-if="record.status === 1">
            <a-tag color="green">已启用</a-tag>
          </template>
          <template v-else>
            <a-tag color="red">已停用</a-tag>
          </template>
        </template>
        <template #action="{ record }">
          <a-space>
            <template v-if="record.status === 1">
              <a-button type="text" size="small" status="warning" @click="handleRunCorrelate(record, false, getList)">
                <template #icon>
                  <icon-stop />
                </template>
                停用
              </a-button>
            </template>
            <template v-else>
              <a-button type="text" size="small" status="success" @click="handleRunCorrelate(record, true, getList)">
                <template #icon>
                  <icon-play-arrow />
                </template>
                启用
              </a-button>
            </template>
            <a-button type="text" size="small" @click="handleBindParamsUpdata(record)"> 修改 </a-button>
            <a-button type="text" status="danger" size="small" @click="handleBindParamsDelete(record)"> 删除 </a-button>
          </a-space>
        </template>
      </a-table>
      <a-pagination
        :total="data.pagination.total"
        :current="data.pagination.pageStart"
        :page-size="data.pagination.pageLength"
        @change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
      ></a-pagination>
    </a-spin>
    <a-modal
      v-if="data.bindVisible"
      title="绑定参数"
      v-model:visible="data.bindVisible"
      width="700px"
      @before-ok="handleBindParamsOk"
    >
      <a-form :model="data.form" ref="formRef">
        <a-form-item label="模板" field="expressId" :rules="[{ required: true, message: '请选择模板' }]">
          <!-- <a-select v-model="data.form.templateName" placeholder="请选择">
            <a-option
              v-for="item in data.thresholdList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select> -->
          <div class="flex flex-col">
            <a-input-search
              style="border-radius: 15px; margin-bottom: 5px; width: 200px"
              placeholder="输入可筛选模板名称"
              size="small"
              v-model="tableSearch"
            />
            <a-table
              style="width: 100%"
              size="mini"
              :scroll="{
                maxHeight: '300px'
              }"
              :columns="columns"
              row-key="id"
              :pagination="false"
              :data="data.thresholdList.filter((item) => item.name.indexOf(tableSearch) > -1)"
              :row-selection="rowSelection"
              :selected-keys="data.selectedKeys"
              @select="handleSelect"
              align="center"
            >
            </a-table>
          </div>
        </a-form-item>
        <a-form-item label="运行模式">
          <a-radio-group v-model="data.form.runMode">
            <a-radio :value="1">运行一次后参数置空</a-radio>
            <a-radio :value="2">周期运行</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="间隔时间" v-if="data.form.runMode === 2">
          <a-input-number v-model="data.form.intervalTime" :min="0">
            <template #append>秒</template>
          </a-input-number>
        </a-form-item>
        <a-form-item label="关联参数">
          <!-- <a-select
              v-model="data.form.paramsList"
              value-key="id"
              placeholder="请选择"
              allow-search
              multiple
          >
            <a-option
                v-for="(item, index) in data.paramsList"
                :key="index"
                :value="item"
                :label="item.paramName + '(' + item.paramCode + ')'"
            ></a-option>
          </a-select> -->
          <a-select
            value-key="paramId"
            multiple
            allow-search
            allow-clear
            placeholder="请选择"
            v-model="data.form.paramsInfo"
          >
            <a-option v-for="item in paramsList" :key="item.id" :value="item" :label="item.paramName"></a-option>
          </a-select>
        </a-form-item>
        <a-row>
          <a-col :span="13">
            <a-form-item label="正常结果范围" field="upperLimit" label-col-flex="120px">
              <a-input-number v-model="data.form.upperLimit" :precision="2" placeholder="请输入"> </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="1" style="text-align: center; line-height: 30px">- </a-col>
          <a-col :span="10">
            <a-form-item hide-label field="lowerLimit" :rules="[{ required: true, message: '请选择' }]">
              <a-input-number v-model="data.form.lowerLimit" :precision="2" placeholder="请输入"> </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="级别">
          <a-select v-model="data.form.alarmLevel" placeholder="请选择">
            <a-option :value="1">1</a-option>
            <a-option :value="2">2</a-option>
            <a-option :value="3">3</a-option>
            <a-option :value="4">4</a-option>
            <a-option :value="5">5</a-option>
            <a-option :value="6">6</a-option>
            <a-option :value="7">7</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { ref, reactive, onMounted, watch } from 'vue'
import { apiAnalysis } from '@/api/analysis'
import { handleRunCorrelate } from '@/views/algorithmBinding/bind/api'
const tableSearch = ref('')
const props = defineProps({
  selectKey: {
    type: Number,
    default: null
  },
  expandedKeys: {
    type: Array,
    default: () => []
  },
  deviceId: {
    type: String,
    default: ''
  },
  paramsList: {
    type: Array,
    default: () => []
  },
  currentSatellite: {
    type: Object,
    default: () => {}
  }
})

const rowSelection = {
  type: 'radio'
}

const columns = [
  {
    title: '告警名称',
    dataIndex: 'name'
  },
  {
    title: '遥测参数',
    render: ({ record }) => {
      return record.paramsList.map((item) => item.paramName).join(',')
    }
  }
  // {
  //   title: "门限等级",
  //   dataIndex: "monitorLevel",
  //   render: ({record}) => {
  //     return record.monitorLevel === 1
  //         ? "一级"
  //         : record.monitorLevel === 2
  //             ? "二级"
  //             : "三级";
  //   },
  // },
  // {
  //   title: "门限警告值",
  //   children: [
  //     {
  //       title: "上限",
  //       dataIndex: "firstLevelMinValue",
  //     },
  //     {
  //       title: "下限",
  //       dataIndex: "firstLevelMaxValue",
  //     },
  //   ],
  // },
  // {
  //   title: "判别模式",
  //   dataIndex: "conditionSet",
  //   render: ({record}) => {
  //     return record.conditionSet === 1
  //         ? "仅门限判断"
  //         : record.conditionSet === 2
  //             ? "工作模式判单"
  //             : "持续时间判断";
  //   },
  // },
]

const data = reactive({
  loading: false,
  tableData: [],
  satelitesList: [],
  columns: [
    {
      title: '序号',
      slotName: 'index',
      width: 60,
      customRender: ({ index }) => {
        return index + 1 + (data.pagination.pageStart - 1) * data.pagination.pageLength
      }
    },
    {
      title: '告警名称',
      dataIndex: 'expressName'
    },
    {
      title: '运行模式',
      dataIndex: 'runMode',
      render: ({ record }) => {
        return +record.runMode === 1 ? '运行一次后参数置空' : '周期运行'
      }
    },
    {
      title: '上限',
      dataIndex: 'upperLimit'
    },
    {
      title: '下限',
      dataIndex: 'lowerLimit'
    },
    {
      title: '告警级别',
      dataIndex: 'alarmLevel',
      render: ({ record }) => {
        return record.alarmLevel + '级'
      }
    },
    {
      title: '运行状态',
      dataIndex: 'status',
      slotName: 'status'
    },
    // {
    //   title: "创建时间",
    //   dataIndex: "createDate",
    // },
    { title: '操作', slotName: 'action', width: 150 }
  ],
  satelliteId: null,
  selectedKeys: [],
  pagination: {
    total: 0,
    pageStart: 1,
    pageLength: 10
  },
  bindVisible: false,
  form: {
    runMode: 1
  },
  thresholdList: [],
  templateFlag: 0,
  paramsList: [] // 参数列表
})
const formRef = ref(null)

const handleBindParamsUpdata = (record) => {
  apiAnalysis.getRelationParamsBindingDetail(record.id).then((res) => {
    if (res.code === 200) {
      data.bindVisible = true
      data.form = res.data
      data.selectedKeys = [res.data.expressId]
      data.form.expressId = res.data.expressId
      data.form.expressName = res.data.expressName
      data.form.upperLimit = +res.data.upperLimit
      data.form.lowerLimit = +res.data.lowerLimit
      data.form.paramsInfo = res.data.params
    }
  })
}

const handleBindParamsDelete = (record) => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      apiAnalysis.deleteRelationParamsBinding(record.id).then((res) => {
        if (res.code === 200) {
          Message.success('删除成功')
          getList()
        }
      })
    }
  })
}

const handleBindPrams = () => {
  data.bindVisible = true
  data.selectedKeys = []
  data.form = {
    runMode: 1
  }
  console.log('props.expandedKeys', props.expandedKeys)
  // apiAnalysis.getParamsListBySatelliteId("1").then((res) => {
  //   data.paramsList = res.data;
  //   console.log("res.data", res.data);
  // });
}

const deleteTime = (index) => {
  data.form.timeList.splice(index, 1)
}

const handleSelect = (rowKeys, rowKey, record) => {
  console.log(rowKeys, 'rowKeys')
  console.log(rowKey, 'rowKey')
  console.log(record, 'record')
  data.selectedKeys = rowKeys
  data.form.expressId = rowKey
  data.form.expressName = record.name
  if (record.conditionSet === 1) {
    data.templateFlag = 1
  } else if (record.conditionSet === 2) {
    data.templateFlag = 2
  } else {
    data.templateFlag = 3
  }
}

const handleBindParamsOk = (done) => {
  formRef.value.validate().then((col) => {
    data.form.parameterList = data.form.paramsInfo.map((item) => {
      return {
        satId: item.satId,
        satCode: item.satCode,
        satName: item.satName,
        paramId: item.paramId,
        paramCode: item.paramCode,
        paramName: item.paramName,
        subsystemId: item.subsystemId,
        subsystemName: item.subsystemName,
        deviceId: item.deviceId,
        deviceCode: item.deviceCode,
        deviceName: item.deviceName
      }
    })
    // data.form.satId = props.currentSatellite.satId;
    data.form.satId = data.form.parameterList[0].satId
    data.form.satName = data.form.parameterList[0].satName
    data.form.satCode = data.form.parameterList[0].satCode
    data.form.subsystemId = data.form.parameterList[0].subsystemId
    data.form.subsystemName = data.form.parameterList[0].subsystemName
    data.form.deviceId = props.deviceId
    data.form.deviceCode = data.form.parameterList[0].deviceCode
    data.form.deviceName = data.form.parameterList[0].deviceName

    console.log(data.form, 'data.form')
    if (!col) {
      const api = data.form.id ? apiAnalysis.updateRelationParamsBinding : apiAnalysis.addRelationParamsBinding

      api(data.form).then((res) => {
        if (res.code === 200) {
          Message.success('绑定成功')
          data.bindVisible = false
          getList()
        } else {
          Message.error('绑定失败')
        }
      })
      done(true)
    } else {
      done(false)
    }
  })
}

const getThresholdList = () => {
  apiAnalysis
    .getRelationParams({
      pageNum: 1,
      pageSize: 100
    })
    .then((res) => {
      if (res.code === 200) {
        data.thresholdList = res.data.list
      }
    })
}

const handlePageChange = (page) => {
  data.pagination.pageStart = page
  getList()
}

const handlePageSizeChange = (size) => {
  data.pagination.pageLength = size
  getList()
}

watch(
  () => props.deviceId,
  () => {
    getList()
  }
)

const getList = () => {
  console.log(props.deviceId, 'props.deviceId')
  data.loading = true
  apiAnalysis
    .getRelationParamsBindingList(Object.assign(data.pagination, { deviceId: props.deviceId }))
    .then((res) => {
      if (res.code === 200) {
        data.loading = false
        data.tableData = res.data.list
        data.pagination.total = +res.data.total
      } else {
        data.loading = false
      }
    })
    .finally(() => {
      data.loading = false
    })
}

onMounted(() => {
  getThresholdList()
  getList()
})
</script>

<style scoped>
:deep(.arco-btn-size-small) {
  padding: 5px;
}
</style>
